<template>
    <div class="profile-container">
        <div class="page-breadcrumb">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>个人中心</el-breadcrumb-item>
                <el-breadcrumb-item>个人资料</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-card class="profile-header" shadow="hover">
            <div class="header-content">
                <div class="avatar-container">
                    <el-upload
                        class="avatar-uploader"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :http-request="handleAvatarUpload"
                    >
                        <div class="avatar-wrapper">
                            <el-avatar 
                                v-if="user.avatar && user.avatar !== ''" 
                                :size="100" 
                                :src="avatarUrl" 
                                :key="avatarKey" 
                                class="user-avatar"
                                @error="handleAvatarError"
                            />
                            <el-avatar v-else :size="100" class="user-avatar">
                                {{ (user.username || 'U').charAt(0).toUpperCase() }}
                            </el-avatar>
                        </div>
                    </el-upload>
                </div>
                <div class="user-info">
                    <h2>{{ user.nickName || user.username || '用户' }}</h2>
                    <p class="user-role">
                        <el-tag size="small" :type="user.role === 'admin' ? 'danger' : 'primary'">
                            {{ user.role === 'admin' ? '管理员' : '普通用户' }}
                        </el-tag>
                    </p>
                    <p class="user-meta">
                        <span><el-icon>
                                <User />
                            </el-icon> ID: {{ user.id || 'N/A' }}</span>
                        <span class="clickable" @click="openEditDialog('email')"><el-icon>
                                <User />
                            </el-icon> {{ user.email || '未设置邮箱' }}</span>
                        <span class="clickable" @click="openEditDialog('phone')"><el-icon>
                                <User />
                            </el-icon> {{ user.phoneNumber || '未设置手机号' }}</span>
                    </p>

                </div>
            </div>
        </el-card>
    </div>

    <el-dialog :title="editType === 'email' ? '修改邮箱' : '修改手机号'" v-model="editDialogVisible" width="405px"
        :close-on-click-modal="false" :align-center="true">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
            <el-form-item v-if="editType === 'email'" label="邮箱" prop="email">
                <el-input v-model="editForm.email" placeholder="请输入新邮箱" />
            </el-form-item>
            <el-form-item v-if="editType === 'phone'" label="手机号" prop="phone">
                <el-input v-model="editForm.phone" placeholder="请输入新手机号" />
            </el-form-item>
            <el-form-item label="验证码" prop="code">
                <el-input v-model="editForm.code" placeholder="请输入验证码" style="width: 180px; margin-right: 8px;" />
                <el-button type="primary">获取验证码</el-button>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">保存</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Plus, Upload } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { useUserStore } from '@/stores/user'

const user = ref({})
const loading = ref(true)
const userStore = useUserStore()
const avatarKey = ref(0) // 用于强制头像组件重新渲染

// 计算属性 - 头像URL
const avatarUrl = computed(() => {
    const avatar = user.value.avatar
    if (avatar && avatar.trim()) {
        console.log('使用头像URL:', avatar)
        return processAvatarUrl(avatar)
    }
    const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    console.log('使用默认头像:', defaultAvatar)
    return defaultAvatar
})

// 头像URL处理函数 - 解决Gitee图床CORS问题
const processAvatarUrl = (url) => {
    if (!url) return url
    // 只要是http开头的都走代理，兼容gitee、oss等
    if (url.startsWith('http')) {
        return `https://images.weserv.nl/?url=${encodeURIComponent(url.replace(/^https?:\/\//, ''))}`
    }
    return url
}

// 编辑邮箱/手机号相关
const editDialogVisible = ref(false)
const editType = ref('email') // 'email' or 'phone'
const editForm = reactive({ email: '', phone: '' })
const editFormRef = ref()
const editRules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
}



function openEditDialog(type) {
    editType.value = type
    editDialogVisible.value = true
    editForm.email = user.value.email || ''
    editForm.phone = user.value.phoneNumber || ''
}

// 头像错误处理
function handleAvatarError(event) {
    console.error('原始头像URL:', user.value.avatar)
    console.error('代理后头像URL:', avatarUrl.value)
    console.error('头像加载失败事件:', event)
}

// 头像上传前的验证
function beforeAvatarUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif' || file.type === 'image/webp'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJpgOrPng) {
        ElMessage.error('头像只能是 JPG、PNG、GIF 或 WebP 格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 处理头像上传
async function handleAvatarUpload(options) {
    const { file } = options
    
    try {
        ElMessage.info('正在上传头像...')
        
        const response = await userApi.uploadAvatar(user.value.id, file)
        
        if (response.isSuccess) {
            // 更新用户头像
            user.value.avatar = response.data
            avatarKey.value += 1
            
            // 更新全局用户状态
            userStore.updateAvatar(response.data)
            
            ElMessage.success('头像上传成功')
        } else {
            ElMessage.error(response.message || '头像上传失败')
        }
    } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('头像上传失败')
    }
}

async function submitEdit() {
    await editFormRef.value.validate()
    const userId = user.value.id
    try {
        if (editType.value === 'email') {
            await userApi.updateEmail(userId, { email: editForm.email })
            user.value.email = editForm.email
            ElMessage.success('邮箱修改成功')
        } else {
            await userApi.updatePhone(userId, { phoneNumber: editForm.phone })
            user.value.phoneNumber = editForm.phone
            ElMessage.success('手机号修改成功')
        }
        editDialogVisible.value = false
    } catch (e) {
        ElMessage.error('修改失败，请重试')
    }
}

onMounted(async () => {
    try {
        loading.value = true
        const data = await userApi.getCurrentUser()
        user.value = data
        console.log('页面加载，用户信息:', data)
        console.log('页面加载，头像URL:', data.avatar)
    } catch (e) {
        ElMessage.error('获取用户信息失败')
    } finally {
        loading.value = false
    }
})
</script>

<style scoped lang="scss">
.clickable {
    cursor: pointer;
    color: #409eff;
    transition: color 0.2s;

    &:hover {
        color: #66b1ff;
        /* 去除下划线 */
        text-decoration: none;
    }
}

// 防止横向滚动条出现，优化自适应布局
.profile-container {
    box-sizing: border-box;
    padding: 24px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
    width: 100%;
    overflow-x: hidden;

    .page-breadcrumb {
        margin-bottom: 20px;
        padding: 8px 0;

        :deep(.el-breadcrumb__item) {
            .el-breadcrumb__inner {
                font-weight: 500;
                color: #606266;

                &.is-link {
                    color: #409eff;
                    font-weight: 500;

                    &:hover {
                        color: #66b1ff;
                    }
                }
            }
        }
    }

    .profile-header {
        margin-bottom: 24px;
        border-radius: 12px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        transition: all 0.3s;
        border: none;
        max-width: 100%;

        &:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.08);
        }

        .header-content {
            display: flex;
            align-items: center;
            padding: 32px;
            background: linear-gradient(45deg, #f1f7fe, #e6f0fd);
            position: relative;
            flex-wrap: wrap;
            min-width: 0;

            &::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 3px;
                background: linear-gradient(to right, #409eff, #67c23a);
            }

            .avatar-container {
                margin-right: 36px;

                .avatar-wrapper {
                    position: relative;
                    display: inline-block;
                    
                    .user-avatar {
                        width: 110px;
                        height: 110px;
                        background-color: #ecf5ff;
                        font-size: 28px;
                        font-weight: 600;
                        color: #409eff;
                        transition: all 0.3s;
                        border: 5px solid #fff;
                        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
                        cursor: pointer;
                    }
                    
                    .avatar-overlay {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 110px;
                        height: 110px;
                        background-color: rgba(0, 0, 0, 0.6);
                        border-radius: 50%;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        color: white;
                        opacity: 0;
                        transition: all 0.3s;
                        cursor: pointer;
                        font-size: 12px;
                        
                        .el-icon {
                            font-size: 20px;
                            margin-bottom: 4px;
                        }
                        
                        &:hover {
                            opacity: 1;
                        }
                    }
                    
                    &:hover .avatar-overlay {
                        opacity: 1;
                    }
                }
            }

            .user-info {
                flex: 1 1 0%;
                min-width: 0;

                h2 {
                    margin: 0 0 16px 0;
                    font-size: 28px;
                    font-weight: 700;
                    background: linear-gradient(135deg, #409eff, #67c23a);
                    -webkit-background-clip: text;
                    background-clip: text;
                    -webkit-text-fill-color: transparent;
                    display: inline-block;
                    position: relative;
                    padding-bottom: 8px;

                    &::after {
                        content: '';
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        width: 40px;
                        height: 3px;
                        background: linear-gradient(135deg, #409eff, #67c23a);
                        border-radius: 3px;
                    }
                }

                .user-role {
                    margin-bottom: 16px;

                    .el-tag {
                        margin-right: 8px;
                        border-radius: 20px;
                        padding: 0 12px;
                        height: 28px;
                        line-height: 26px;
                        border: none;
                        box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
                        font-weight: 500;
                    }
                }

                .user-meta {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 12px;
                    min-width: 0;

                    span {
                        display: flex;
                        align-items: center;
                        background-color: #f0f7ff;
                        padding: 8px 16px;
                        border-radius: 24px;
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
                        transition: all 0.3s;
                        color: #555;
                        font-weight: 500;
                        font-size: 14px;

                        &:hover {
                            background-color: #e0f0ff;
                            transform: translateY(-2px);
                            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                        }

                        .el-icon {
                            margin-right: 8px;
                            color: #409eff;
                            font-size: 16px;
                        }
                    }
                }
            }
        }
    }

    .profile-content {
        background-color: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.07);
        animation: fadeIn 0.5s ease-out;
        max-width: 100%;

        // .card-header 样式已移除
        .info-label {
            font-size: 13px;
            color: #7b8190;
            margin-bottom: 4px;
            font-weight: 600;
        }

        .info-value {
            font-size: 17px;
            color: #22223b;
            font-weight: 500;
            word-break: break-all;
        }
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
}
</style>
